//
//  CALFoodAmountViewController.m
//  CalCounter
//
//  Created by Toan Nguyen on 9/10/13.
//  Copyright (c) 2013 Le thanh Lam. All rights reserved.
//

#import "CALFoodAmountViewController.h"
#import "NSString+Ex.h"
#import "NSDate+Ex.h"
#import "DataHelper.h"
#import "DateTimeView.h"
@interface CALFoodAmountViewController ()<UITextFieldDelegate>{
    __weak IBOutlet UILabel *_msgLabel;
    IBOutlet UITextField *_amountTextField;
    double _foodCalUnit;
}

@end

@implementation CALFoodAmountViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.isEditMode = NO;
    }
    return self;
}



- (IBAction)saveTapped:(id)sender {
    if([_amountTextField.text length] == 0){
        [[[UIAlertView alloc] initWithTitle:@"" message:NSLocalizedString(@"CannotEmpty", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
        return;
    }
    
    _amountTextField.text = [_amountTextField.text stringByReplacingOccurrencesOfString:@"," withString:@"."];
    static NSString *floatRegex = @"^(?:[1-9]\\d*|0)?(?:\\.\\d+)?$";
    if(![_amountTextField.text isMatchRegex:floatRegex]){
        [[[UIAlertView alloc] initWithTitle:@"" message:NSLocalizedString(@"InvalidValue", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
        return;
    }
    
    if([_amountTextField.text doubleValue] > 9999){
        [[[UIAlertView alloc] initWithTitle:@"" message:NSLocalizedString(@"BigValue", nil) delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
        return;
    }
    
    
    float value = [_amountTextField.text floatValue];
    self.selectedFood.cals = _foodCalUnit * value / 100.0f;
    
    if(self.isEditMode){
        NSInteger eatingId = [self.delegate eatingIdForUpdateFood];
        [[DataHelper sharedDatabase] updateFoodAmount:self.selectedFood eatingId:eatingId];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(eatingIdForUpdateFood)]){
            NSInteger eatingId = [self.delegate eatingIdForUpdateFood];
            [[DataHelper sharedDatabase] updateFood:self.selectedFood eatingId:eatingId];
        }
        
        if(self.delegate != nil && [self.delegate respondsToSelector:@selector(didSelectFood:)]){
            [self.delegate didSelectFood:self.selectedFood];
        }
        
        NSArray *vcArray = self.navigationController.viewControllers;
        UIViewController *vc = [vcArray objectAtIndex:[vcArray count] - 3];
        [self.navigationController popToViewController:vc animated:YES];
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = self.selectedFood.foodName;
    _foodCalUnit = [[DataHelper sharedDatabase] getFoodCalUnit:self.selectedFood.foodId];
    if(self.isEditMode){
        _msgLabel.text = [NSString stringWithFormat:@"%1.1f (%1.1f%@/100g)",self.selectedFood.cals,_foodCalUnit,NSLocalizedString(@"cals", nil)];
        _amountTextField.text = [NSString stringWithFormat:@"%1.1f",self.selectedFood.cals * 100/_foodCalUnit];
        [_amountTextField becomeFirstResponder];
    }else{
        _msgLabel.text = [NSString stringWithFormat:@"0 (%1.1f%@/100g)",_foodCalUnit,NSLocalizedString(@"cals", nil)];
    }
    
   
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)changeAmountWithText:(NSString *)text{
    if([text length] == 0){
        _msgLabel.textColor = [UIColor grayColor];
        _msgLabel.text = [NSString stringWithFormat:@"0 (%1.1f%@/100g)",_foodCalUnit,NSLocalizedString(@"cals", nil)];
    }else{
        text = [text stringByReplacingOccurrencesOfString:@"," withString:@"."];
        static NSString *floatRegex = @"^(?:[1-9]\\d*|0)?(?:\\.\\d+)?$";
        if([text isMatchRegex:floatRegex]){
            if([text doubleValue] > 9999){
                _msgLabel.textColor = [UIColor redColor];
                _msgLabel.text = NSLocalizedString(@"BigValue", nil);
            }else{
                _msgLabel.textColor = [UIColor blackColor];
                float value = [text floatValue];
                double result = _foodCalUnit * value / 100.0f;
                _msgLabel.text = [NSString stringWithFormat:@"%1.1f (%1.1f%@/100g)",result,_foodCalUnit,NSLocalizedString(@"cals", nil)];
            }
        }else{
            _msgLabel.textColor = [UIColor redColor];
        }
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    [self changeAmountWithText:text];
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    return YES;
}
#pragma mark -


@end
